package com.jubotech.framework.config;

import Jubo.JuLiao.IM.Wx.Proto.ChatRoomPushNotice;
import Jubo.JuLiao.IM.Wx.Proto.TalkToFriendTask;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.JsonFormat;
import com.jubotech.business.web.dao.WxContactDao;
import com.jubotech.business.web.domain.SysConfig;
import com.jubotech.business.web.domain.WxContactInfo;
import com.jubotech.business.web.service.SysConfigService;
import com.jubotech.framework.netty.async.AsyncTaskService;
import com.jubotech.framework.netty.utils.MessageUtil;
import com.jubotech.framework.netty.utils.MsgIdBuilder;
import com.jubotech.framework.netty.utils.NettyConnectionUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 机器人服务类
 */
@Service
public class RobotService {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private NettyConnectionUtil nettyConnectionUtil;


    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private WxContactDao wxContactDao;

    // 控制任务是否运行的标志
    private volatile boolean running = false;

    /**
     * 启动机器人任务
     */
    @Async
    public void startRobotTask() {
        if (running) {
            return; // 防止任务重复启动
        }

        running = true;
        try {
            while (running) {
                executeRobotTask();

                // 获取配置中的间隔时间
                long interval = getRobotInterval()*1000L;
                Thread.sleep(interval);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            running = false;
        }
    }

    /**
     * 停止机器人任务
     */
    public void stopRobotTask() {
        running = false;
    }

    /**
     * 执行机器人任务逻辑
     */
    private void executeRobotTask() {
        try {
            SysConfig robotConfig = sysConfigService.getByConfig("robotConfig");
            if (robotConfig != null && robotConfig.getEnable() == 1) {
                JSONObject jsonObject = JSON.parseObject(robotConfig.getValue());
                System.out.println(jsonObject);
                // 这里添加机器人任务的具体逻辑
                String wechatId=jsonObject.getString("cid");
                ChannelHandlerContext chx = nettyConnectionUtil.getClientChannelHandlerContextByUserId(wechatId);
                System.out.println("cid"+jsonObject.getString("cid"));
                if (null != chx) {
                    System.out.println("设备在线");
                    //获取设备群列表
                    List<WxContactInfo> contactinfoByWxidAndType = wxContactDao.findContactinfoByWxidAndType(wechatId, 1);
                    System.out.println(contactinfoByWxidAndType);
                    for (WxContactInfo wxContactInfo : contactinfoByWxidAndType) {
                        //黑名单模式
                        String black = jsonObject.getString("blackFlag");
                        if (black.isEmpty()){
                            return;
                        }
                        JSONArray names = jsonObject.getJSONArray("names");
                        if (black.equals("true")){
                            //黑名单模式
                            for (int i = 0; i < names.size(); i++) {
                                String name = names.getString(i);
                                if (name.trim().equals(wxContactInfo.getNickname().trim())) {
                                    //在黑名单，退出
                                    return;
                                }
                            }
                        }else{
                            //白名单模式
                            for (int i = 0; i < names.size(); i++) {
                                String name = names.getString(i);
                                if (!name.trim().equals(wxContactInfo.getNickname().trim())) {
                                    //不在白名单，退出
                                    return;
                                }
                            }
                        }
                        ByteString byteString = ByteString.copyFromUtf8(jsonObject.getString("template"));
                        TalkToFriendTask.TalkToFriendTaskMessage.Builder bd = TalkToFriendTask.TalkToFriendTaskMessage.newBuilder();
                        bd.setContent(byteString);
                        bd.setContentType(TransportMessageOuterClass.EnumContentType.Text);
                        // 发给谁
                        bd.setFriendId(wxContactInfo.getFriendid());
                        bd.setMsgId(MsgIdBuilder.getId());
                        TalkToFriendTask.TalkToFriendTaskMessage req = bd.build();
                        // 发给手机端
                        MessageUtil.sendMsg(chx, TransportMessageOuterClass.EnumMsgType.TalkToFriendTask, null, null, req);
                    }
                }else{
                    System.out.println("设备不在线");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取机器人执行间隔时间
     */
    private long getRobotInterval() {
        try {
            SysConfig robotConfig = sysConfigService.getByConfig("robotConfig");
            if (robotConfig != null && robotConfig.getEnable() == 1) {
                JSONObject jsonObject = JSON.parseObject(robotConfig.getValue());
                return Long.valueOf(jsonObject.getString("interval"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 60000L; // 默认60秒
    }
}
